<link rel="import" href="../../bower_components/paper-button/paper-button.html">
<link rel="import" href="../../bower_components/neon-animation/animations/scale-up-animation.html">
<link rel="import" href="../../bower_components/neon-animation/animations/fade-out-animation.html">
 
<script src="../../bower_components/xterm.js/dist/xterm.js"></script>
<script src="../../bower_components/xterm.js/dist/addons/fit/fit.js"></script>
<script src="../../bower_components/xterm.js/dist/addons/fullscreen/fullscreen.js"></script>


<style>

</style>
<dom-module id="xterm-dialog">
    <link rel="import" type="css" href="../../bower_components/xterm.js/dist/xterm.css">
    <template>
        <style>
            .terminal .xterm-viewport {
            /* On OS X this is required in order for the scroll bar to appear fully opaque */
                background-color: transparent !important;
            }
            .terminal {
                background-color: transparent !important;
            }
            :host {
                display: block;
                width: 100% !important;
                z-index: 999999;
                top: 0;
                left: 0;
            }

            paper-dialog-scrollable {
                margin: 0;
                padding: 0;
            }

            h2 {
                line-height: 32px;
                background-color: #fff !important;
                color: #000;
                padding: 8px 16px;
                margin: 0;
            }

            h2 iron-icon {
                margin-right: 8px;
            }

            #dialogModal {
              width: 100% !important;
              padding: 0px;
            }

            #terminal-container {
                padding: 4px;
                background-color: rgba(0,0,0,0.85) !important;
                color: rgba(255,255,255,.8);
                font-family: monospace;
                font-weight: 700;
                height: calc(100% - 56px);
                position: fixed;
                width:100%;
            }

            :host(.inparent) #terminal-container {
                padding: 4px;
                min-height: 300px;
                position: relative !important;
                width: calc(100% - 8px);
                overflow: scroll;
            }

            .icon-buttons {
                float: right;
                margin: 0;
            }
        </style>
        <div class="icon-buttons" hidden$=[[!controls]]>
            <!--paper-button dialog-confirm><iron-icon icon="icons:remove">minimize</iron-icon></paper-button-->
            <paper-button on-tap="remove"><iron-icon icon="icons:close">close</iron-icon></paper-button>
        </div>
        <h2 hidden$=[[!controls]]>
            <iron-icon icon="vaadin:terminal"></iron-icon> {{target.name}}
        </h2>
        <div id="terminal-container">
        </div>
    </template>

    <script>
        (function() {
            'use strict';

            Polymer({
                is: 'xterm-dialog',

                properties: {
                    term: {
                        type: Object
                    },
                    target: {
                        type: Object
                    },
                    height: {
                        type: Number,
                        value: 0
                    },
                    reason: {
                        type: String,
                        value: null
                    },
                    controls: {
                        type: Boolean,
                        value: true
                    }
                },
                listeners: {
                    'iron-overlay-closed': '_modalClosed'
                },
                ready: function() {
                    console.debug('xterm loaded');
                },
                attached: function() {
                    console.debug('xterm attached');
                    this.socket = document.querySelector('mist-app').shadowRoot.querySelector('mist-socket');
                    
                    this.term = new Terminal({
                        cursorBlink: true
                    });

                    var terminalContainer = this.shadowRoot.querySelector('#terminal-container');
                    this.term.open(terminalContainer, true);

                    var newCols, newRows;
                    [newCols, newRows] = this.resizeTerminal();

                    var ips = [].concat(this.target.public_ips).concat(this.target.private_ips);
                    if (ips[0])
                        this.term.write('Connecting to ' + ips[0] + '...\r\n');

                    var socket = this.socket;
                    this.term.on('data', function (data, ev) {
                        socket.send('msg', 'shell', 'shell_data', [data]);
                    });
                    socket.send('sub', 'shell');

                    var payload = {
                        cols: newCols,
                        rows: newRows,
                        cloud_id: '',
                        machine_id: '',
                        host: ''
                    };

                    if (this.target.job_id) {
                        payload['job_id'] = this.target.job_id;
                        payload['provider'] = 'docker';
                        payload['host'] = '';
                    } else if (this.target.provider === 'lxd'){
                        payload['cloud_id'] = this.target.cloud;
                        payload['machine_id'] = this.target.id;
                        payload['provider'] = 'lxd';
                        payload['host'] = ips[0];
                        this.set("style.position", "fixed");
                    }
                    else {
                        payload['cloud_id'] = this.target.cloud;
                        payload['machine_id'] = this.target.id;
                        payload['host'] = ips[0];
                        this.set("style.position", "fixed")
                    }

                    socket.send('msg', 'shell', 'shell_open', [payload]);

                    socket.set('term', this.term);

                    // Add event handler for window resize
                    var that = this;
                    this.resizeHandler = function() {
                        that.resizeTerminal();
                    };
                    window.addEventListener("resize", this.resizeHandler,{passive: true});
                },

                resizeTerminal: function(newRows, newCols) {
                    var prevCols = this.term.cols, prevRows = this.term.rows;
                    if (newRows && newCols)
                        this.term.resize(newCols, newRows);
                    else {
                        this.term.fit();
                        if (!newRows)
                            newRows = this.term.rows;
                        if (!newCols)
                            newCols = this.term.cols;
                    }
                    if (newCols != prevCols || newRows != prevRows) {
                        console.log('resize term', newCols, newRows);
                        this.socket.send(
                            'msg',
                            'shell',
                            'shell_resize',
                            [newCols, newRows]);
                    }
                    return [newCols, newRows];
                },
                detached: function() {
                    console.debug('xterm detached');
                    var socket = document.querySelector('mist-app').shadowRoot.querySelector('mist-socket');
                    socket.send('uns', 'shell');
                    window.removeEventListener("resize", this.resizeHandler);
                },
                _closeDialog: function(e) {
                    //this.$.dialogModal.close();
                    this.remove();
                },
                _modalClosed: function(e) {
                    if (e.srcElement.id == 'dialogModal') {
                        console.log(this.$.dialogModal.closingReason);
                        this.dispatchEvent(new CustomEvent('confirmation', { bubbles: true, composed: true, detail: {
                            response: this.$.dialogModal.closingReason,
                            reason: this.reason
                        } }));

                    }
                    this._closeDialog();
                }
            });
        })();
    </script>
</dom-module>
